<template>
  <div class="app-bar" :class="[
    `app-bar--${variant}`,
    { 'app-bar--fixed': fixed },
    { 'app-bar--has-tabs': tabs && tabs.length > 0 }
  ]" :style="{ height: `${actualHeight}px` }">
    <!-- 安全区域适配 -->
    <div class="app-bar__safe-area" v-if="safeArea"></div>
    
    <div class="app-bar__container">
      <!-- 左侧区域 -->
      <div class="app-bar__left">
        <slot name="left">
          <button
            v-if="showBack"
            class="app-bar__back-btn"
            @click="handleBack"
          >
            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path d="M15 18L9 12L15 6" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
            </svg>
          </button>
          <div v-if="$slots.leftIcon" class="app-bar__left-icon">
            <slot name="leftIcon"></slot>
          </div>
        </slot>
      </div>

      <!-- 中间标题区域 -->
      <div class="app-bar__center">
        <slot name="center">
          <div v-if="title" class="app-bar__title" :class="{ 'app-bar__title--bold': titleBold }">
            {{ title }}
          </div>
          <div v-if="subtitle" class="app-bar__subtitle">
            {{ subtitle }}
          </div>
        </slot>
      </div>

      <!-- 右侧区域 -->
      <div class="app-bar__right">
        <slot name="right">
          <button
            v-if="showClose"
            class="app-bar__close-btn"
            @click="handleClose"
          >
            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path d="M18 6L6 18M6 6L18 18" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
            </svg>
          </button>
          <div v-if="$slots.rightIcon" class="app-bar__right-icon">
            <slot name="rightIcon"></slot>
          </div>
        </slot>
      </div>
    </div>

    <!-- 底部 Tab 区域 -->
    <div v-if="tabs && tabs.length > 0" class="app-bar__tabs" :class="{ 'app-bar__tabs--scrollable': scrollable }">
      <div class="app-bar__tabs-wrapper" :class="{ 'app-bar__tabs-wrapper--scrollable': scrollable }">
        <button
          v-for="(tab, index) in tabs"
          :key="getTabKey(tab, index)"
          :ref="el => setTabRef(el, index)"
          class="app-bar__tab"
          :class="{ 'app-bar__tab--active': isActiveTab(tab.value) }"
          @click="handleTabClick(tab.value)"
        >
          <span class="app-bar__tab-label" :ref="el => setTabLabelRef(el, index)">
            {{ tab.label }}
          </span>
          <span 
            v-if="isActiveTab(tab.value)" 
            class="app-bar__tab-indicator"
            :style="getIndicatorStyle(tab.value)"
          ></span>
        </button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, ref, watch, nextTick, onMounted } from 'vue'

export interface TabItem {
  label: string
  value: string | number
}

interface Props {
  // 标题
  title?: string
  subtitle?: string
  titleBold?: boolean
  
  // 显示控制
  showBack?: boolean
  showClose?: boolean
  fixed?: boolean
  shadow?: boolean
  safeArea?: boolean
  
  // 样式变体
  variant?: 'default' | 'transparent' | 'gradient'
  
  // 高度
  height?: number
  
  // 背景色（自定义）
  backgroundColor?: string
  textColor?: string

  // Tab 相关
  tabs?: TabItem[]
  scrollable?: boolean
  modelValue?: string | number
}

interface Emits {
  (e: 'back'): void
  (e: 'close'): void
  (e: 'update:modelValue', value: string | number): void
  (e: 'tab-change', value: string | number): void
}

const props = withDefaults(defineProps<Props>(), {
  title: '',
  subtitle: '',
  titleBold: true,
  showBack: false,
  showClose: false,
  fixed: true,
  shadow: false,
  safeArea: true,
  variant: 'default',
  height: 56,
  tabs: () => [],
  scrollable: false
})

const emit = defineEmits<Emits>()

// Tab 相关的 refs
const tabRefs = ref<(HTMLElement | null)[]>([])
const tabLabelRefs = ref<(HTMLElement | null)[]>([])
const indicatorStyle = ref<{ width: string; left: string }>({ width: '0px', left: '50%' })

// 计算 AppBar 的实际高度（包含 tabs）
const actualHeight = computed(() => {
  if (props.tabs && props.tabs.length > 0) {
    // AppBar 高度(56px) + Tab 高度(48px) = 104px
    return props.height + 48
  }
  return props.height
})

// 判断是否为激活的 tab
const isActiveTab = (value: string | number) => {
  return props.modelValue === value
}

// 获取 tab 的唯一 key
const getTabKey = (tab: TabItem, index: number) => {
  return tab.value ?? `tab-${index}`
}

// 设置 tab ref
const setTabRef = (el: any, index: number) => {
  if (el && el instanceof HTMLElement) {
    tabRefs.value[index] = el
  }
}

// 设置 label ref
const setTabLabelRef = (el: any, index: number) => {
  if (el && el instanceof HTMLElement) {
    tabLabelRefs.value[index] = el
  }
}

// 更新指示器样式
const updateIndicatorStyle = async () => {
  if (!props.tabs || props.tabs.length === 0) return
  
  const activeIndex = props.tabs.findIndex(tab => tab.value === props.modelValue)
  if (activeIndex === -1) return

  await nextTick()
  
  const labelEl = tabLabelRefs.value[activeIndex]
  const tabEl = tabRefs.value[activeIndex]
  
  if (labelEl && tabEl) {
    const labelRect = labelEl.getBoundingClientRect()
    const tabRect = tabEl.getBoundingClientRect()
    
    // 指示器宽度为文字宽度的 70%，最小 20px，最大不超过文字宽度
    const labelWidth = labelRect.width
    const indicatorWidth = Math.min(Math.max(labelWidth * 0.7, 20), labelWidth * 0.9)
    
    // 计算指示器位置：文字中心相对于 tab 的位置
    // label 相对于 tab 的偏移
    const labelOffsetLeft = labelRect.left - tabRect.left
    const labelCenter = labelOffsetLeft + labelWidth / 2
    
    // 因为使用了 transform: translateX(-50%)，所以 left 应该是中心位置
    indicatorStyle.value = {
      width: `${indicatorWidth}px`,
      left: `${labelCenter}px`
    }
  }
}

// 获取指示器样式
const getIndicatorStyle = (value: string | number) => {
  if (!isActiveTab(value)) {
    return { width: '0px', opacity: '0' }
  }
  
  return {
    width: indicatorStyle.value.width,
    left: indicatorStyle.value.left,
    opacity: '1'
  }
}

// 监听 modelValue 变化，更新指示器
watch(() => props.modelValue, () => {
  updateIndicatorStyle()
}, { immediate: true })

// 监听 tabs 变化，更新指示器
watch(() => props.tabs, () => {
  nextTick(() => {
    updateIndicatorStyle()
  })
}, { deep: true })

// 组件挂载后更新指示器
onMounted(() => {
  updateIndicatorStyle()
  // 延迟一下确保 DOM 完全渲染
  setTimeout(updateIndicatorStyle, 100)
})

const handleBack = () => {
  emit('back')
}

const handleClose = () => {
  emit('close')
}

const handleTabClick = (value: string | number) => {
  if (props.modelValue === value) return // 避免重复触发
  
  emit('update:modelValue', value)
  emit('tab-change', value)
  
  // 更新指示器位置
  nextTick(() => {
    updateIndicatorStyle()
  })
}
</script>

<style scoped>
.app-bar {
  position: relative;
  width: 100%;
  background: #ffffff;
  z-index: 100;
  display: flex;
  flex-direction: column;
}

.app-bar--has-tabs .app-bar__container {
  flex-shrink: 0;
  height: 56px;
}

.app-bar--fixed {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
}

.app-bar--transparent {
  background: transparent;
}

.app-bar--gradient {
  background: linear-gradient(135deg, #1a1a1a 0%, #2d2d2d 100%);
  color: #ffffff;
}

.app-bar--gradient .app-bar__title,
.app-bar--gradient .app-bar__subtitle,
.app-bar--gradient .app-bar__back-btn,
.app-bar--gradient .app-bar__close-btn {
  color: #ffffff;
}

/* 安全区域适配 */
.app-bar__safe-area {
  height: env(safe-area-inset-top);
  background: inherit;
}

.app-bar__container {
  display: flex;
  align-items: center;
  height: 100%;
  padding: 0 12px;
}

/* 左侧区域 */
.app-bar__left {
  display: flex;
  align-items: center;
  min-width: 40px;
  height: 100%;
}

.app-bar__back-btn,
.app-bar__close-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 40px;
  height: 40px;
  padding: 0;
  border: none;
  background: transparent;
  color: #1e293b;
  cursor: pointer;
  border-radius: 8px;
  transition: all 0.2s ease;
}

.app-bar__back-btn:hover,
.app-bar__close-btn:hover {
  background: rgba(0, 0, 0, 0.05);
}

.app-bar__back-btn:active,
.app-bar__close-btn:active {
  background: rgba(0, 0, 0, 0.1);
  transform: scale(0.95);
}

.app-bar__left-icon,
.app-bar__right-icon {
  display: flex;
  align-items: center;
  height: 100%;
}

/* 中间标题区域 */
.app-bar__center {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-width: 0;
  padding: 0 16px;
  text-align: center;
}

.app-bar__title {
  font-size: 16px;
  font-weight: 500;
  color: #1e293b;
  line-height: 1.4;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 100%;
}

.app-bar__title--bold {
  font-weight: 600;
}

.app-bar__subtitle {
  font-size: 11px;
  color: #64748b;
  line-height: 1.4;
  margin-top: 2px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 100%;
}

/* 右侧区域 */
.app-bar__right {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  min-width: 40px;
  height: 100%;
  gap: 8px;
}


/* 暗色模式支持 */
@media (prefers-color-scheme: dark) {
  .app-bar--default {
    background: #1e293b;
    color: #ffffff;
  }

  .app-bar--default .app-bar__title {
    color: #ffffff;
  }

  .app-bar--default .app-bar__subtitle {
    color: #94a3b8;
  }

  .app-bar--default .app-bar__back-btn,
  .app-bar--default .app-bar__close-btn {
    color: #ffffff;
  }

  .app-bar--default .app-bar__back-btn:hover,
  .app-bar--default .app-bar__close-btn:hover {
    background: rgba(255, 255, 255, 0.1);
  }
}

/* 动画效果 */
.app-bar {
  transition: background-color 0.3s ease;
}

/* 无障碍支持 */
.app-bar__back-btn:focus,
.app-bar__close-btn:focus {
  outline: 2px solid rgba(59, 130, 246, 0.5);
  outline-offset: 2px;
}

/* 底部 Tab 区域 */
.app-bar__tabs {
  flex-shrink: 0;
  height: 48px;
  background: inherit;
}

.app-bar__tabs-wrapper {
  display: flex;
  align-items: center;
  width: 100%;
}

/* 不滚动模式：均匀分布（通过子元素的 flex: 1 实现） */

/* 滚动模式：横向滚动 */
.app-bar__tabs-wrapper--scrollable {
  overflow-x: auto;
  overflow-y: hidden;
  -webkit-overflow-scrolling: touch;
  scrollbar-width: none;
  -ms-overflow-style: none;
}

.app-bar__tabs-wrapper--scrollable::-webkit-scrollbar {
  display: none;
}

.app-bar__tab {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 10px 12px;
  border: none;
  background: transparent;
  color: #64748b;
  font-size: 15px;
  font-weight: 500;
  cursor: pointer;
  white-space: nowrap;
  transition: color 0.3s cubic-bezier(0.4, 0, 0.2, 1),
              font-weight 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
}

/* 不滚动模式：flex 均匀分布 */
.app-bar__tabs-wrapper:not(.app-bar__tabs-wrapper--scrollable) .app-bar__tab {
  flex: 1;
  min-width: 0;
  width: 0; /* 确保每个 tab 宽度完全一致 */
}

/* 滚动模式：最小宽度 */
.app-bar__tabs-wrapper--scrollable .app-bar__tab {
  min-width: fit-content;
  flex-shrink: 0;
  padding: 10px 16px;
}

.app-bar__tab:hover {
  color: #1e293b;
  background: rgba(0, 0, 0, 0.02);
}

.app-bar__tab--active {
  color: #3b82f6;
  font-weight: 600;
}

.app-bar__tab-label {
  line-height: 1.4;
  position: relative;
  z-index: 1;
  transition: transform 0.2s ease;
  margin-bottom: 6px;
}

.app-bar__tab--active .app-bar__tab-label {
  transform: scale(1.02);
}

/* 指示器样式 - 短下划线，只在文字下方 */
.app-bar__tab-indicator {
  position: absolute;
  bottom: 6px;
  height: 3px;
  background: linear-gradient(90deg, #3b82f6 0%, #60a5fa 100%);
  border-radius: 2px;
  transition: width 0.3s cubic-bezier(0.4, 0, 0.2, 1),
              left 0.3s cubic-bezier(0.4, 0, 0.2, 1),
              opacity 0.2s ease;
  transform: translateX(-50%);
  box-shadow: 0 1px 3px rgba(59, 130, 246, 0.3);
}

/* Gradient 变体的 Tab 样式 */

.app-bar--gradient .app-bar__tab {
  color: rgba(255, 255, 255, 0.7);
}

.app-bar--gradient .app-bar__tab:hover {
  color: #ffffff;
  background: rgba(255, 255, 255, 0.1);
}

.app-bar--gradient .app-bar__tab--active {
  color: #ffffff;
}

.app-bar--gradient .app-bar__tab-indicator {
  background: linear-gradient(90deg, #ffffff 0%, rgba(255, 255, 255, 0.9) 100%);
  box-shadow: 0 1px 3px rgba(255, 255, 255, 0.3);
}


/* 暗色模式支持 */
@media (prefers-color-scheme: dark) {
  .app-bar--default .app-bar__tabs {
    border-top-color: rgba(255, 255, 255, 0.1);
  }

  .app-bar--default .app-bar__tab {
    color: #94a3b8;
  }

  .app-bar--default .app-bar__tab:hover {
    color: #ffffff;
    background: rgba(255, 255, 255, 0.1);
  }

  .app-bar--default .app-bar__tab--active {
    color: #60a5fa;
  }

  .app-bar--default .app-bar__tab-indicator {
    background: linear-gradient(90deg, #60a5fa 0%, #93c5fd 100%);
    box-shadow: 0 1px 3px rgba(96, 165, 250, 0.3);
  }
}
</style>

